import Taro from '@tarojs/taro';
import utils from './util';
import Api from './Api';
/**
 * @param url//请求url的key
 * @param method//请求方式
 * @param datas//请求所传参数
 * @param header//设置请求头
 */
class AjaxRequest {
  constructor() {
    this.isLoading = true;
    this.isShowMessage = true;
    this.queue = {}; // 当前在请求的接口list
  }
  post(url, datas, header, isLoading, isShowMessage) {
    return this.request(url, "POST", datas, header, isLoading, isShowMessage);
  }
  get(url, datas, header, isLoading, isShowMessage) {
    return this.request(url, "GET", datas, header, isLoading, isShowMessage);
  }
  getHeader(header) {
    let newHeader = { "content-type": "application/json" }
    if (typeof (header) === 'boolean' && header) {
      newHeader = { 'content-type': 'application/x-www-form-urlencoded' }
    } else if (typeof (header) === 'object' && header !== null) {
      newHeader = Object.assign(newHeader, header, {})
    }
    return newHeader
  }
  request(api, method, datas, header, isLoading = true, isShowMessage = true) {
    this.isLoading = isLoading;
    this.isShowMessage = isShowMessage;
    return new Promise((reselove, reject) => {
      if (!Api[api]) {
        console.error("api is undefined!!!")
        reject("api is undefined!!!");
        return;
      }
      console.log('请求api---------url:' + process.env.API_URL + api);
      console.log('请求参数' + JSON.stringify(datas || {}));
      if (this.isLoading && Object.keys(this.queue).length === 0) {
        utils.showLoading(); // 如果没有请求过 显示loading
      }
      // 请求前 增加请求队列
      this.isLoading && (this.queue[api] = api); // 存入队列中
      try {
        Taro.request({
          url: process.env.API_URL + api,
          data: datas || {},
          method: method,
          header: this.getHeader(header) || {},
          success: (res) => {
            console.log('请求结果', res);
            if (res.statusCode === 200 && res.data.code === 1) {
              reselove(res.data);
            } else {
              this.isShowMessage && setTimeout(() => {
                utils.showtoast(res.data && res.data && (res.data.datas || res.data.msg) || '服务器异常，请稍后再试');
              }, 100);
              reject(res.data);
            }
          },
          fail: (e) => {
            console.log(e)
            this.isShowMessage && setTimeout(() => {
              utils.showtoast('网络错误，请稍后再试');
            });
            console.log('请求失败', e);
            reject(e.data);
          },
          complete: (e) => {
            console.log(e)
            delete this.queue[api];
            if (Object.keys(this.queue).length === 0) {
              utils.hideLoading(); // 当队列被清空隐藏掉即可
            }
          }
        })
      } catch (e) {
        console.log(e);
        setTimeout(() => {
          utils.showtoast('程序出错');
        });
        reject(e.data);
      }
    });
  }
}
export default new AjaxRequest;

